package com.xiangban.yanglaodajie_platform.service;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.xiangban.yanglaodajie_platform.config.WxParameterConfig;
import com.xiangban.yanglaodajie_platform.utils.CommonUtils;
import com.xiangban.yanglaodajie_platform.utils.WXConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

@Service
public class PayService {
    @Autowired
    private WxParameterConfig wxParameterConfig;

    //支付方式
    public static final String TRADE_TYPE_APP = "APP";
    public String payBack(String resXml) {
        System.out.println("resXml******:"+resXml);
        WXConfigUtil config = null;
        try {
            config = new WXConfigUtil();
        } catch (Exception e) {
            e.printStackTrace();
        }
        WXPay wxpay = new WXPay(config);
        String xmlBack = "";
        Map<String, String> notifyMap = null;
        try {
            notifyMap = WXPayUtil.xmlToMap(resXml);         // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {//验证签名是否有效，有效则进一步处理
                String return_code = notifyMap.get("return_code");//状态
                System.out.println("return_code******"+return_code);
                String out_trade_no = notifyMap.get("out_trade_no");//商户订单号
                if (return_code.equals("SUCCESS")) {
                    if (out_trade_no != null) {
                        // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户的订单状态从退款改成支付成功
                        // 注意特殊情况：微信服务端同样的通知可能会多次发送给商户系统，所以数据持久化之前需要检查是否已经处理过了，处理了直接返回成功标志

                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        //log.info("微信手机支付回调失败订单号:{}", out_trade_no);
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                }
                return xmlBack;
            } else {
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
                //失败的数据要不要存储？
                //log.error("手机支付回调通知签名错误");
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            }
        } catch (Exception e) {
            //log.error("手机支付回调通知失败", e);
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return xmlBack;
    }

    public Map<String,String> doUnifiedOrder(Map<String,Object> parameter)  {
        // 发起微信支付
        WXPay wxpay = null;
        Map<String, String> result = new HashMap<>();
        try{
            //处理订单金额
            DecimalFormat df = new DecimalFormat();
            double price = Double.parseDouble(df.format(parameter.get("price")));
            int money = (int)(price * 100);
            WXConfigUtil config = new WXConfigUtil();
            wxpay = new WXPay(config);
            Map<String, String> data = new HashMap<>();
            data.put("appid", wxParameterConfig.getAPP_ID());  //appid
            data.put("mch_id", wxParameterConfig.getMCH_ID());
            data.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符串
            data.put("body", "积分充值");
            data.put("out_trade_no", parameter.get("order_no").toString()); // 订单唯一编号, 不允许重复
            data.put("total_fee", String.valueOf(money)); // 订单金额, 单位分
            data.put("spbill_create_ip", CommonUtils.getHostIp()); // 下单ip
            data.put("notify_url", wxParameterConfig.getCALLBACK_URL()); // 订单结果通知, 微信主动回调此接口
            data.put("trade_type", TRADE_TYPE_APP); // 固定填写
            String key = wxParameterConfig.getAPP_KEY();
            String sign = WXPayUtil.generateSignature(data,key);
            data.put("sign", sign);
            Map<String, String> response = wxpay.unifiedOrder(data);
            String returnCode = response.get("return_code");
            System.out.println("returnCode:"+returnCode);
            if (!"SUCCESS".equals(returnCode)) {
                return null;
            }
            String resultCode = response.get("result_code");
            System.out.println("resultCode:"+resultCode);
            if (!"SUCCESS".equals(resultCode)) {
                return null;
            }
            String prepay_id = response.get("prepay_id");
            System.out.println("prepay_id:"+prepay_id);
            if (prepay_id == null) {
                return null;
            }
            //  前端调起微信支付必要参数
//            String packages = "prepay_id=" + prepay_id;
            Map<String, String> wxPayMap = new HashMap<String, String>();
            wxPayMap.put("appid", config.getAppID());
            wxPayMap.put("timestamp", System.currentTimeMillis()/1000+"");
            wxPayMap.put("noncestr", WXPayUtil.generateNonceStr());
            wxPayMap.put("prepayid", prepay_id);
            wxPayMap.put("partnerid",config.getMchID());
            wxPayMap.put("package","Sign=WXPay");
            String packageSign  = WXPayUtil.generateSignature(wxPayMap, config.getKey());
            wxPayMap.put("sign", packageSign );
            result.putAll(wxPayMap);
            return result;
        }catch (Exception e){
            System.out.printf(e.getMessage());

        }
        return null;
    }
}
